const db = uniCloud.databaseForJQL()
export const favMapper = {
	async getFavorites(userId) {
		if(!userId){
			throw new Error('用户未登录')
		}
		let res =await db.collection('zgj-fav')
			.where('user_id=="' + userId + '"')
			.get()
		if (res.errCode !== 0) {
			console.log(res)
			uni.showModal({
				title: '错误信息',
				content: '读取收藏数据失败',
				showCancel: false
			})
			throw new Error('读取收藏数据失败')
		}
		return res.data.length > 0 ? res.data[0] : null
	},
	async addFavorite(userId,channelId){
		if(!userId){
			throw new Error('用户未登录')
		}
		var doc =await this.getFavorites(userId)
		if(doc===null){//insert
			db.collection('zgj-fav').add({user_id:userId,channel_ids:[channelId]})
		}
		else{
			if(doc.channel_ids.indexOf(channelId)<0){
				doc.channel_ids.push(channelId)
				db.collection('zgj-fav').doc(doc._id).update({user_id:userId,channel_ids:doc.channel_ids})
			}
		}
	},
	
	async removeFavorite(userId,channelId){
		if(!userId){
			throw new Error('用户未登录')
		}
		var doc =await this.getFavorites(userId)
		if(doc){
			let idx = doc.channel_ids.indexOf(channelId)
			if(idx>=0){
				doc.channel_ids.splice(idx,1)
				db.collection('zgj-fav').doc(doc._id).update({user_id:userId,channel_ids:doc.channel_ids})
			}
		}
	}
}